#include "threadpool.h"
#define __BIG_FILE_SIZE__ (100*1024*1024) // 大文件边界

// 服务端
int getsCommand(int sockfd,char *cwd,char *filename){                                  

    // 接收文件名
    int ret = 0;
    char recvname[1024] = {0};
    int name_len = 0;
    recvn(sockfd,&name_len,sizeof(name_len));
    recvn(sockfd,recvname,name_len);

    // 接收文件大小
    unsigned long filelen = 0;
    recvn(sockfd,&filelen,sizeof(filelen));

    char full_path[1024] = {0};
    snprintf(full_path,100,"%s/%s",cwd,filename);
    printf("file_path = %s\n",full_path);
    // 打开文件
    // 若存在文件，打开失败
    int filefd = open(full_path,O_RDWR|O_CREAT|O_EXCL,0666);
    unsigned long cursize = 0;
    //打开失败，文件已经存在
    if(filefd == -1){
        filefd = open(full_path,O_RDWR);
        struct stat state;
        fstat(filefd,&state);
        cursize = state.st_size;
        lseek(filefd,cursize,SEEK_SET);
    }

    // 发送当前文件大小
    ret = sendn(sockfd,&cursize,sizeof(cursize));
    printf("ret =  %d\n",ret);

    if(filelen  > __BIG_FILE_SIZE__){
        int ret = 0;
        char buf[4096];
        while(cursize < filelen){
            bzero(buf,sizeof(buf));
            unsigned long remain = filelen - cursize;
            int recv_len = remain < sizeof(buf)? remain : sizeof(buf);

            ret = recvn(sockfd,buf,recv_len);
            if(ret <= 0) break; 


            write(filefd,buf,ret);
            cursize += ret;
            printf("接收进度：%5.2f%%\r",100.00*cursize / filelen);
            fflush(stdout);
        }
    }else{
        char buf[1024] = {0};
        while(cursize < filelen){
            int data_len = 0;
            int ret = recvn(sockfd,(char *)&data_len,sizeof(data_len));
            if(ret <= 0) break;

            ret = recvn(sockfd,buf,data_len);
            if(ret <= 0) break;

            write(filefd,buf,data_len);
            cursize += data_len;
            printf("接收进度：%5.2f%%\r",100.00*cursize/filelen);
            fflush(stdout);
        }
    }
    printf("接收完成！文件总字节数：%lu\n",cursize);
    close(filefd);
    return 0;
}

